package com.example.mybatisdemo.controller;

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@RequestMapping("/export")
@RestController
public class ExportController {


    @GetMapping("/word-table")
    public void exportWordWithTable(HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=table_data.docx");

        XWPFDocument document = new XWPFDocument();
        XWPFParagraph titleParagraph = document.createParagraph();
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText("这是一个标题");
        titleRun.setBold(true); // 设置为粗体
        titleParagraph.setAlignment(ParagraphAlignment.LEFT); // 设置标题居中对齐
        // 将标题的字体大小设置为16
        titleRun.setFontSize(16);

        // 创建段落
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("This is a Word document with a table.");

        // 创建表格
        XWPFTable table = document.createTable();
        table.getRow(0).getCell(0).setText("ID");
        table.getRow(0).addNewTableCell().setText("Name");
        table.getRow(0).addNewTableCell().setText("Description");

        table.createRow().getCell(0).setText("1");
        table.getRow(1).getCell(1).setText("John Doe");
        table.getRow(1).getCell(2).setText("Software Developer");

        table.createRow().getCell(0).setText("2");
        table.getRow(2).getCell(1).setText("Jane Doe");
        table.getRow(2).getCell(2).setText("Project Manager");



        // 添加图片
        String imgFile = "D:\\workspace\\demo\\mybatis-demo\\src\\main\\resources\\static\\1.jpg"; // 图片路径
        FileInputStream fis = new FileInputStream(imgFile);
        XWPFParagraph p2 = document.createParagraph();
        XWPFRun r2 = p2.createRun();
            r2.addPicture(fis,
                    XWPFDocument.PICTURE_TYPE_JPEG,
                    imgFile,
                    Units.toEMU(200),
                    Units.toEMU(200));
        document.write(response.getOutputStream());
        document.close();
    }
}
